﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using TpWeb.Domain.Repositories;
using TpWeb.Models;

namespace TpWeb.Controllers
{
    public class FiasController : Controller
    {
        private readonly ICountryRepository _countryRepository;
        private IFiasRepository _fiasRepository;

        public FiasController(ICountryRepository countryRepository, IFiasRepository fiasRepository)
        {
            _fiasRepository = fiasRepository;
            _countryRepository = countryRepository;
        }

        [HttpPost]
        public JsonResult GetCountriesJSON(string term, int maxCount)
        {
            var q = from c in _countryRepository.All
                    where c.Name.Contains(term)
                    orderby c.Name
                    select new CountryViewModel() { Code = c.Id, Name = c.Name };

            var res = q.Take(5).ToArray();

            return Json(res);
        }

        [HttpGet]
        public JsonResult GetAddrObj(string id)
        {
            var r = _fiasRepository.GetAddrObject(id);
            var jr = Json(r, JsonRequestBehavior.AllowGet);
            return jr;
        }

        [HttpPost]
        public JsonResult GetRegions(string term, int count, string guid = null)
        {
            var res = _fiasRepository.SelectRegions(term, count, guid);
            return Json((res));
        }

        [HttpPost]
        public JsonResult GetDistricts(string term, int count, string pGuid)
        {
            var res = _fiasRepository.SelectDistricts(term, count, parentGuid: pGuid);
            return Json((res));
        }

        [HttpPost]
        public JsonResult GetTowns(string term, int count, string pGuid, int? regCode = null)
        {
            var res = _fiasRepository.SelectTowns(term, count, parentGuid: pGuid, regCode: regCode);
            return Json((res));
        }
        
        [HttpPost]
        public JsonResult GetLocality(string term, int count, string pGuid, int? regCode = null)
        {
            var res = _fiasRepository.SelectLocality(term, count, parentGuid: pGuid, regCode: regCode);
            return Json((res));
        }

        [HttpPost]
        public JsonResult GetStreets(string term, int count, string pGuid, int? regCode = null)
        {
            var res = _fiasRepository.SelectStreets(term, count, parentGuid: pGuid, regCode: regCode);
            return Json((res));
        }
    }
}
